import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { FastifyReply } from 'fastify';
import { ApiException } from '../exceptions/api.exception';
import { ResponseDto } from '../response';

@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<FastifyReply>();

    // check api exection
    const status =
      exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    // set json response
    response.header('Content-Type', 'application/json; charset=utf-8');

    // prod env will not return internal error message
    const code =
      exception instanceof ApiException ? (exception as ApiException).getErrorCode() : status;

    let message = '服务器异常，请稍后再试';
    message = exception instanceof HttpException ? exception.message : `${exception}`;

    const result = new ResponseDto(code, null, message);
    response.status(status).send(result);
  }
}
